package com.tbit.uqbike.tergateway.wa206pkg;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.tbit.uqbike.TerGatewayMain;
import com.tbit.uqbike.protocol.ATerPkg;
import com.tbit.uqbike.protocol.AnalyzeImpl.AProtocol;
import com.tbit.uqbike.protocol.AnalyzeImpl.WA206DeEnCoder;
import com.tbit.uqbike.service.db.DbService;
import com.tbit.uqbike.tergateway.config.TerGatewayConfig;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.entity.AConnInfo;
import com.tbit.uqbike.tergateway.entity.TerPointData;
import com.tbit.uqbike.tergateway.entity.TerTempData;
import com.tbit.uqbike.tergateway.pojo.TerInfo;
import com.tbit.uqbike.tergateway.pojo.TerPoint;
import com.tbit.uqbike.util.ByteUtil;
import com.tbit.uqbike.util.ConstDefine;
import com.tbit.uqbike.util.StringUtil;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.LinkedList;

/**
 * Created by MyWin on 2017/4/27.
 */
public class Login extends ATerPkg {
    private static Logger logger = LoggerFactory.getLogger(Login.class);

    @JSONField(name = "时间", format = "yyyy-MM-dd HH:mm:ss")
    public Date dt;
    @JSONField(name = "重启原因")
    public byte bootReason;
    @JSONField(name = "IMSI")
    public String imsi;
    @JSONField(name = "IMEI")
    public String imei;
    @JSONField(name = "功能码")
    public String funCode;
    @JSONField(name = "厂家编码")
    public String factoryCode;
    @JSONField(name = "软件版本号")
    public String softVersion;

    @Override
    public String toString() {
        return "CommPkg{" +
                "signPkg='" + signPkg + '\'' +
                ", mno='" + mno + '\'' +
                ", head=" + head +
                ", dt=" + dt +
                ", bootReason=" + bootReason +
                ", imsi='" + imsi + '\'' +
                ", imei='" + imei + '\'' +
                ", funCode='" + funCode + '\'' +
                ", factoryCode='" + factoryCode + '\'' +
                ", softVersion='" + softVersion + '\'' +
                '}';
    }

    public static String getTerPointDataMsg(String mno, String rebootCode) {
        TerPointData data = new TerPointData();
        data.mno = mno;
        data.datas = new LinkedList<>();
        TerPoint tp = new TerPoint();
        tp.setTerIdent(mno);
        tp.setDt(new Date());
        tp.setDataType(0x201a);
        tp.setDataValue(rebootCode);
        data.datas.add(tp);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msgId", ConstDefine.MQ_MSG_ID_TER_PP);
        jsonObject.put("feedback", StringUtil.Empty);
        jsonObject.put("data", data);
        return jsonObject.toJSONString();
    }

    @Override
    public void doBusiness() {
        logger.debug(this.toString());
        // 记录一下埋点数据
        TerGatewayData.statDataTask.addStatData(TerGatewayConfig.pointDataStatKey, getTerPointDataMsg(this.mno, ByteUtil.ByteToHexString(this.bootReason)));
        // 检查离线指令
        TerTempData terTempData = TerGatewayData.getTerTempDataByMno(this.mno);

        DbService dbService = TerGatewayMain.getDbService();
        TerInfo terExist = dbService.getTerInfoByMno(this.mno);
        if (terExist == null) {
            terExist = this.getTerInfo();

            //更新是否支持头盔
            if (this.head instanceof WA206Head) {
                WA206Head wa206Head = (WA206Head) this.head;
                int reserve = wa206Head.reserve;
                int helmetInfo = getHelmetInfo(reserve);
                terExist.setHelmetInfo(helmetInfo);
            }

            dbService.insertTerInfo(terExist);
        } else {
            if (needUpdate(terExist)) {
                TerInfo newInfo = this.getTerInfo();
                //更新是否支持头盔
                if (this.head instanceof WA206Head) {
                    WA206Head wa206Head = (WA206Head) this.head;
                    int reserve = wa206Head.reserve;
                    int helmetInfo = getHelmetInfo(reserve);
                    newInfo.setHelmetInfo(helmetInfo);
                }
                terTempData.updateTerInfo(newInfo);
            }
        }

        if (terTempData.getOfflineOrderFlag()) {
            terTempData.checkOfflineOrder();
        }
    }

    @Override
    public boolean autoRsp() {
        return true;
    }

    @Override
    public ByteBuf getRsp(AConnInfo info, AProtocol protocol) {
        return ((WA206DeEnCoder) protocol).getLoginInfoRsp(info, this);
    }

    @Override
    public String getMachineNO() {
        return this.mno;
    }

    private TerInfo getTerInfo() {
        TerInfo info = new TerInfo();
        info.setFactoryCode(this.factoryCode);
        info.setFunCode(this.funCode);
        info.setImei(this.imei);
        info.setImsi(this.imsi);
        info.setJoinTime(new Date());
        info.setMachineNO(this.mno);
        info.setSoftVersion(this.softVersion);
        return info;
    }

    private boolean needUpdate(TerInfo terExist) {
        if (this.mno.equals(terExist.getMachineNO())
                && this.imei.equals(terExist.getImei())
                && this.imsi.equals(terExist.getImsi())
                && this.funCode.equals(terExist.getFunCode())
                && this.factoryCode.equals(terExist.getFactoryCode())
                && this.softVersion.equals(terExist.getSoftVersion())
                && terExist.getJoinTime() != null) {
            return false;
        } else {
            return true;
        }
    }

    private int getHelmetInfo(int reserve) {
        return (reserve >> 4 & 0x1);
    }

}
